package com.eorchis.module.planopinion.ui.controller;

import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eorchis.constants.RoleConstants;
import com.eorchis.core.service.IBaseService;
import com.eorchis.core.springext.mvc.SessionConstant;
import com.eorchis.core.ui.commond.ResultState;
import com.eorchis.core.ui.controller.AbstractBaseController;
import com.eorchis.module.basedata.domain.BaseData;
import com.eorchis.module.basedata.service.cache.BaseDataCacheUtil;
import com.eorchis.module.department.domain.Department;
import com.eorchis.module.planopinion.bean.PlanOpinionExportBean;
import com.eorchis.module.planopinion.domain.PlanOpinion;
import com.eorchis.module.planopinion.service.IPlanOpinionService;
import com.eorchis.module.planopinion.ui.commond.PlanOpinionQueryCommond;
import com.eorchis.module.planopinion.ui.commond.PlanOpinionValidCommond;
import com.eorchis.module.remind.domain.Remind;
import com.eorchis.module.remind.service.IRemindService;
import com.eorchis.module.role.domain.Role;
import com.eorchis.module.trainingplan.domain.TrainingPlan;
import com.eorchis.module.trainingplan.service.ITrainingPlanService;
import com.eorchis.module.trainingplan.ui.commond.TrainingPlanValidCommond;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: PlanOpinionController<br>
 * Description: 填写计划意见实体表管理控制器<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * @author RongSL
 * @createDate 2016-07-12
 * @version $Revision$
 */
@Controller("planOpinionController")
@RequestMapping(value = PlanOpinionController.MODULE_PATH)
public class PlanOpinionController 
		extends AbstractBaseController<PlanOpinionValidCommond,PlanOpinionQueryCommond> 
{
	// 模块页面根路径
	public static final String MODULE_PATH = "/module/planopinion";
	// 填写计划意见实体表接口
	@Autowired
	@Qualifier("main.java.com.eorchis.module.planopinion.service.impl.PlanOpinionServiceImpl")
	private IPlanOpinionService planOpinionService;

	// 提醒表接口
	@Resource(name = "com.eorchis.module.remind.service.impl.RemindServiceImpl")
	private IRemindService remindService;
	
	@Resource(name = "com.eorchis.module.basedata.service.cache.BaseDataCacheUtil")
	private BaseDataCacheUtil baseDataCacheUtil;

	// 培训计划接口
	@Autowired
	@Qualifier("com.eorchis.module.trainingplan.service.impl.TrainingPlanServiceImpl")
	private ITrainingPlanService trainingPlanService;
	
	public IBaseService getService() {
		return planOpinionService;
	}

	public String getModulePath() {
		return MODULE_PATH;
	}
	
	public String getPageBasePath() {
		return "/portal/project/module/planopinion";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/lookOpinion")
	public void lookOpinion(PlanOpinionQueryCommond queryCommond){
		List<PlanOpinionValidCommond> list=(List<PlanOpinionValidCommond>) planOpinionService.findList(queryCommond);
		queryCommond.setResultList(list);
	}
	
	/**
	 * 新增反馈意见
	 * */
	@RequestMapping("/writeOpinion")
	public void writeOpinion(HttpServletRequest request,@ModelAttribute("resultList")PlanOpinionQueryCommond queryCommond,@ModelAttribute("ResultSate") ResultState resultState){
		try {
			Department currentScope = (Department) request.getSession().getAttribute(SessionConstant.CURRENT_SCOPE);
			queryCommond.setSearchDeptId(currentScope.getDeptID());
			//查找下发表ID
			String iid=planOpinionService.findIssuedId(queryCommond);
			Map<String, BaseData> baseDataMap =  baseDataCacheUtil.getBaseData();
			Date date=new Date();
			if(PropertyUtil.objectNotEmpty(iid)){
				PlanOpinionValidCommond vCommond;
				if(queryCommond.getOpinionState().equals(PlanOpinion.OPINION_STATE_YES)){
					for(int i=0;i<queryCommond.getOpinionTitleCodes().length;i++){
						vCommond=new PlanOpinionValidCommond();
						vCommond.setActiveState(1);
						vCommond.setOpinionState(PlanOpinion.OPINION_STATE_YES);
						vCommond.setCreateDate(date);
						vCommond.setIssuedId(iid);
						vCommond.setOpinionTitle(baseDataMap.get(queryCommond.getOpinionTitleCodes()[i]));
						vCommond.setOpinionValue(queryCommond.getOpinionTitleValues()[i]);
						planOpinionService.save(vCommond);
					}
				}else{
					vCommond=new PlanOpinionValidCommond();
					vCommond.setOpinionState(PlanOpinion.OPINION_STATE_NO);
					vCommond.setActiveState(1);
					vCommond.setCreateDate(date);
					vCommond.setIssuedId(iid);
					planOpinionService.save(vCommond);
				}
				
				//更新培训计划反馈状态
				planOpinionService.updatePlanIssuedState(iid);
				
				TrainingPlanValidCommond tp=new TrainingPlanValidCommond();
				tp.setPlanId(queryCommond.getSearchPlanId());
				tp=trainingPlanService.findTrainingPlan(tp);
				tp.setIssuedState(TrainingPlan.ISSUEDSTATE_F);
				trainingPlanService.update(tp);
				
				try {
					/**
					 * 添加提醒
					 * 
					 * @Date 2016-05-12
					 * @author RongSL
					 * @Params 提醒类型，培训班名称，承办部委名称，提醒分类
					 * */
					remindService.remindOperate(Remind.TJYJ, tp.getClassName(),currentScope.getDeptName(),RoleConstants.ROLE_ZZB_NAME, tp.getPlanId(), Remind.PXB);
				}catch (Exception e){
					System.out.println("培训计划下发提醒接口出错了！");
				}
			}else{
				resultState.setMessage("未下发此计划！");
				resultState.setState(ResultState.RESULT_STATE_FAIL);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 意见导出
	 * @author RongSL
	 * @Date 2016-07-21
	 * */
	@RequestMapping("/opinionExport")
	public void opinionExport(PlanOpinionQueryCommond queryCommond,HttpServletResponse response,HttpServletRequest request,@ModelAttribute("ResultState")ResultState resultState){
		try{
			// 第一步，创建一个webbook，对应一个Excel文件
			HSSFWorkbook wb = new HSSFWorkbook();
			// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
			HSSFSheet sheet;
			HSSFRow row;
			HSSFCell cell;
			// 设置字体样式
			HSSFFont font = wb.createFont();
			font.setFontName("黑体");
			font.setFontHeightInPoints((short) 18);// 设置字体大小
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示

			HSSFFont font2 = wb.createFont();
			font2.setFontName("楷体");
			font2.setFontHeightInPoints((short) 13);// 设置字体大小

			HSSFFont font3 = wb.createFont();// 题组样式
			font3.setFontName("微软雅黑");
			font3.setFontHeightInPoints((short) 15);// 设置字体大小

			// 设置单元格样式
			HSSFCellStyle style0 = wb.createCellStyle();// 标题样式
			style0.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION); // 居中对齐
			style0.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style0.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style0.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style0.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style0.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style0.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style0.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style0.setFillForegroundColor(HSSFColor.WHITE.index);// 单元格背景色
			style0.setFont(font);
			HSSFCellStyle style1 = wb.createCellStyle();// 单选样式
			style1.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 创建一个居中格式
			style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style1.setFillForegroundColor(HSSFColor.LIME.index);// 单元格背景色
			style1.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style1.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style1.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style1.setFont(font2);
			HSSFCellStyle style2 = wb.createCellStyle();// 多选样式
			style2.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 创建一个居中格式
			style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style2.setFillForegroundColor(HSSFColor.CORNFLOWER_BLUE.index);// 单元格背景色
			style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style2.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style2.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style2.setFont(font2);
			HSSFCellStyle style3 = wb.createCellStyle();
			style3.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 创建一个居中格式
			style3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style3.setFillForegroundColor(HSSFColor.GOLD.index);// 单元格背景色
			style3.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style3.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style3.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style3.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style3.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style3.setFont(font2);

			HSSFCellStyle style4 = wb.createCellStyle();
			style4.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
			style4.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style4.setFillForegroundColor(HSSFColor.SKY_BLUE.index);// 单元格背景色
			style4.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style4.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style4.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style4.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style4.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style4.setFont(font3);

			int width=0;//当前列

			List<?> opinionType=planOpinionService.getOpinionType();
			String []oType;
			Role r=(Role) request.getSession().getAttribute("currentRole");
			if(r.getRoleCode().equals(RoleConstants.ROLE_CODE_BW_ADMIN)){
				Department d=(Department) request.getSession().getAttribute("currentScope");
				queryCommond.setSearchDeptName(d.getDeptName());
			}
			
			List<PlanOpinionExportBean> summaryList=planOpinionService.opinionSummary(queryCommond);//意见汇总数据
			Map<String,List<PlanOpinionExportBean>> detailedList=planOpinionService.opinionDetailed(queryCommond);//意见明细数据
			
			//创建意见汇总表
			sheet=wb.createSheet("意见汇总表");
			for (int z = 0; z <= 20; z++) {
				sheet.setColumnWidth(z, 6000);
			}
			sheet.setDefaultRowHeight((short) 432);// 默认单元格高度
			int typeNum=opinionType.size();//意见类型数量
			int summaryWidth=2+typeNum;//实际宽度
			//第一行
			row=sheet.createRow(width);
			sheet.addMergedRegion(new CellRangeAddress(0, 0, width, summaryWidth));
			cell=row.createCell(width);
			cell.setCellValue("意见汇总表");
			cell.setCellStyle(style0);
			//第二行
			row=sheet.createRow(1);
			cell=row.createCell(width);
			cell.setCellValue("培训计划名称");
			cell.setCellStyle(style4);
			width++;
			for(int i=0;i<typeNum;i++){
				Object[] objs = (Object[])opinionType.get(i);
				int o=0;
				oType=new String[objs.length];
				for(Object ob:objs){
					if(ob instanceof String ){
						oType[o]=(String)ob;
					}
					o++;
				}
				cell=row.createCell(width);
				cell.setCellValue(oType[1]);
				cell.setCellStyle(style4);
				width++;
			}
			cell=row.createCell(width);
			cell.setCellValue("下发总数");
			cell.setCellStyle(style4);
			width++;
			cell=row.createCell(width);
			cell.setCellValue("反馈总数");
			cell.setCellStyle(style4);
			//第三行
			Iterator<PlanOpinionExportBean> ite=summaryList.iterator();
			int i=2;
				while(ite.hasNext()){
					PlanOpinionExportBean p=ite.next();
					width=0;
					row=sheet.createRow(i);
					cell=row.createCell(width);
					cell.setCellValue(p.getClassName());
					cell.setCellStyle(style2);
					width++;
					for(int j=0;j<typeNum;j++){
						cell=row.createCell(width);
						cell.setCellValue(p.getEachCount()[j]);
						cell.setCellStyle(style2);
						width++;
					}
					cell=row.createCell(width);
					cell.setCellValue(p.getIssuedCount());
					cell.setCellStyle(style2);
					width++;
					cell=row.createCell(width);
					cell.setCellValue(p.getOpinionCount());
					cell.setCellStyle(style2);
					i++;
				}
			
			//创建意见明细表
			for(String c:detailedList.keySet()){
				String sheetName="";
				TrainingPlanValidCommond tr=new TrainingPlanValidCommond();
				tr.setPlanId(detailedList.get(c).get(0).getPlanId());
				tr=trainingPlanService.findTrainingPlan(tr);
				if(tr.getPublishState().equals(TrainingPlan.PUBLISHSTATE_Y)){
					sheetName=detailedList.get(c).get(0).getClassName();
				}else{
					sheetName=detailedList.get(c).get(0).getClassName()+"-讨论稿";
				}
				sheet = wb.createSheet(sheetName);
				for (int z = 0; z <= 20; z++) {
					if(z==1)
						sheet.setColumnWidth(z, 8000);
					else
						sheet.setColumnWidth(z, 6000);
				}
				sheet.setDefaultRowHeight((short) 432);// 默认单元格高度
				summaryWidth=1+typeNum;//实际宽度
				width=0;
				//第一行
				row = sheet.createRow(0);
				sheet.addMergedRegion(new CellRangeAddress(0, 0, width, summaryWidth));
				cell=row.createCell(0);
				cell.setCellValue(detailedList.get(c).get(0).getClassName()+"-反馈意见明细");
				cell.setCellStyle(style0);

				//第二行
				row=sheet.createRow(1);
				cell=row.createCell(width);
				cell.setCellValue("部门编号");
				cell.setCellStyle(style4);
				width++;
				cell=row.createCell(width);
				cell.setCellValue("反馈时间");
				cell.setCellStyle(style4);
				width++;
				for(int j=0;j<typeNum;j++){
					Object[] objs = (Object[])opinionType.get(j);
					int o=0;
					oType=new String[objs.length];
					for(Object ob:objs){
						if(ob instanceof String ){
							oType[o]=(String)ob;
						}
						o++;
					}
					cell=row.createCell(width);
					cell.setCellValue(oType[1]);
					cell.setCellStyle(style4);
					width++;
				}
				//第三行
				ite=detailedList.get(c).iterator();
				int k=2;
				while(ite.hasNext()){
					PlanOpinionExportBean p=ite.next();
					width=0;
					row=sheet.createRow(k);
					cell=row.createCell(width);
					cell.setCellValue(p.getDepName());
					cell.setCellStyle(style2);
					width++;
					cell=row.createCell(width);
					cell.setCellValue(p.getFeedbackDateStr());
					cell.setCellStyle(style2);
					width++;
					for(int j=0;j<typeNum;j++){
						cell=row.createCell(width);
						cell.setCellValue(p.getOpinionValues()[j]);
						cell.setCellStyle(style2);
						width++;
					}
					k++;
				}
			}
			if (summaryList.size()> 0) {
				try {
					response.reset();
					response.setContentType("application/x-msdownload");
					response.setHeader("Content-Disposition", "attachment; filename=" + new String(("意见汇总表").getBytes("gb2312"), "ISO-8859-1") + ".xls");
					ServletOutputStream outStream = null;
					outStream = response.getOutputStream();
					wb.write(outStream);
					outStream.close();
					resultState.setState(ResultState.RESULT_STATE_SUCCESS);
					resultState.setMessage("导出成功!");
				} catch (Exception e1) {
					e1.printStackTrace();
					resultState.setState(ResultState.RESULT_STATE_FAIL);
					resultState.setMessage("导出失败！!");
				}
			} else {
				resultState.setState(ResultState.RESULT_STATE_FAIL);
				resultState.setMessage("暂无数据!");
				response.setCharacterEncoding("GB2312"); 
				PrintWriter pw=response.getWriter();
				pw.write("<script>alert('暂无数据');window.opener='';window.open('', '_self', '');window.close();</script>");
				pw.close();
			}
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("意见导出失败！");
			resultState.setMessage("意见导出失败，请联系管理员！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 查看反馈意见详情
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@RequestMapping("/detailed")
	public void detailed(@ModelAttribute("result")PlanOpinionExportBean bean,@ModelAttribute("ResultSate") ResultState resultState){
		try{
			PlanOpinionExportBean bean1=planOpinionService.Detailed(bean);//意见明细数据
			bean.setApplyNum(bean1.getApplyNum());
			bean.setClassName(bean1.getClassName());
			bean.setOpinionTitles(bean1.getOpinionTitles());
			bean.setOpinionValues(bean1.getOpinionValues());
			bean.setPlanDay(bean1.getPlanDay());
			bean.setJointName(bean1.getJointName());
			bean.setUndertakeName(bean1.getUndertakeName());
			bean.setDepName(bean1.getDepName());
			bean.setDepId(bean1.getDepId());
			bean.setFeedbackDateStr(bean1.getFeedbackDateStr());
			bean.setStartPlanDateStr(bean1.getStartPlanDateStr());
			bean.setEndPlanDateStr(bean1.getEndPlanDateStr());
			resultState.setMessage("查看成功!");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			resultState.setMessage("查看意见异常，请联系管理员！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}
}
